import {Command} from '../constant';
import Taro from '@tarojs/taro';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';
import api from 'api';
export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    loadUserInfo() {
      let itemStr = Taro.getStorageSync('b2b-wechat@login');
      if (itemStr.user) {
        dispatch({
          type: Command.init,
          payload: {
            main: {
              customer: itemStr.user,
            },
          },
        });
      } else {
        Taro.navigateTo({
          url: '/pages/package-C/login/index',
        });
      }
    },
    async getMemberBase() {
      const result = await api.MemberController.getMemberBase();
      let memberCardType = 'noMember';
      if (result.isAquamarineMember) {
        memberCardType = 'lanjing';
      }
      if (result.isCrystalMember) {
        memberCardType = 'chijing';
      }
      if (result.isAquamarineMember && result.isCrystalMember) {
        memberCardType = 'shuangchong';
      }
      dispatch({
        type: Command.init,
        payload: {
          main: {
            memberCardType,
            memberInfo: result,
          },
        },
      });
      return memberCardType;
    },
    //微信支付
    async goToWeixinPay(openid) {
      const {
        main: {selectCard},
      } = getData();

      try {
        const context = await api.payController.wxPayPurchaseCardOrderForLittleProgram({openid, cardId: selectCard});
        //@ts-ignore
        const {timeStamp, nonceStr, signType, paySign} = context;
        await Taro.requestPayment({
          timeStamp,
          nonceStr,
          //@ts-ignore
          package: context.package,
          signType,
          paySign,
          success: async (res) => {
            Taro.showToast({
              title: '会员开通成功!',
              icon: 'none',
            });
            let back = false;
            let task = Taro.getStorageSync('task');
            if (task) task = JSON.parse(task);
            console.log(task, '我是任务');
            if (task && task?.taskInfoVO?.conditionsType == 5) {
              await api.TaskCenterController.completedTask({
                id: task.id,
              });
              Taro.removeStorageSync('task');
              setTimeout(() => {
                Taro.showToast({
                  title: `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ''}${
                    ['积分', '优惠券', '商品'][task.taskInfoVO.rewardType]
                  }`,
                  icon: 'none',
                });
              }, 1000);
            }
            setTimeout(() => {
              if (back) {
                Taro.navigateBack();
              } else {
                Taro.switchTab({
                  url: '/pages/index/index',
                });
              }
            }, 2000);
          },
          fail: function (res) {},
        });
      } catch (e) {
        console.log(e);
      }
    },

    // async getMemberEquityNum() {
    //   const result = await api.MemberController.getMemberEquityNum();
    //   if (result) {
    //     dispatch({
    //       type: Command.init,
    //       payload: {
    //         main: {
    //           lanjingLength: result.blueLevelRightsVOList.length || '0',
    //           chijingLength: result.redLevelRightsVOList.length || '0',
    //         },
    //       },
    //     });
    //   }
    // },
    async getMemberPrivilege() {
      const {
        main: {selectId},
      } = getData();
      const result = await api.BenefitsPageController.getBenefits({rightsType: selectId});
      action.commonChange('main.lanjings', result.blueLevelRightsVOList);
      action.commonChange('main.chijings', result.redLevelRightsVOList);
    },
    async page() {
      const {
        main: {selectId},
      } = getData();
      const result = await api.MemberOpenController.getOpenMemberList({rightsType: selectId});
      if (Array.isArray(result)) {
        const lanjingList = [];
        const chijingList = [];
        result.forEach((e) => {
          (e.memberType == 0 ? lanjingList : chijingList).push(e);
        });
        if (lanjingList.length > 0) action.commonChange('main.selectCard', lanjingList[0].cardId);
        action.commonChange('main.lanjingList', lanjingList);
        action.commonChange('main.chijingList', chijingList);
      }
    },
    async page2(memberType: number = 0) {
      const {
        main: {isAquamarineMember, isCrystalMember},
      } = getData();
      // let memberType = null;
      // if (isAquamarineMember && isCrystalMember) {
      //   //双会员
      //   memberType = 2;
      // } else if (isAquamarineMember && !isCrystalMember) {
      //   //蓝晶会员
      //   memberType = 0;
      // } else if (!isAquamarineMember && isCrystalMember) {
      //   //赤晶会员
      //   memberType = 1;
      // }
      let params = {
        enterWay: 0,
        memberType: memberType, //会员类型：0-蓝晶会员 1-赤晶会员 2双会员
      };
      const res = await api.OnecategoryController.findOnecategoryList(params); //查询权益类目-通道
      action.commonChange('main.list', res);
    },
    /**
     * 初始化
     */
    async query() {},
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageAMemberOpenMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
